package thread;

import java.util.ArrayList;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/26 19:42
 * 同步锁
 * 分为方法锁和对象锁
 * 一般使用锁的是变化的量（增删改）
 */
public class ThreadSynchronized {
    public static void main(String[] args) {
       test1();
       test2();
    }

    public static void test1(){
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }

    public static void test2(){
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
